<?php


namespace common\services;


use DateTime;

class WebOssUploadService
{

    //oss 配置
    public static function ossSign($maxSize = 0)
    {
        $id = \Yii::$app->params['oss_conf']['accessKeyId'];          // 请填写您的AccessKeyId。
        $key = \Yii::$app->params['oss_conf']['accessKeySecret'];     // 请填写您的AccessKeySecret。
        $host = \Yii::$app->params['oss_conf']['cndHost'];

        //默认10M单文件
        $maxSize = $maxSize ?: 1024 * 1024 * 10;

        $now = time();
        $expire = 60;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = self::gmtIso8601($end);

        //最大文件大小.用户可以自己设置
        $condition = array(0 => 'content-length-range', 1 => 0, 2 => $maxSize);
        $conditions[] = $condition;

        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response = array();
        $response['accessid'] = $id;
        $response['host'] = $host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        return $response;
    }

    private static function gmtIso8601($time)
    {
        $dtStr = date("c", $time);
        $mydatetime = new DateTime($dtStr);
        $expiration = $mydatetime->format(DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration . "Z";
    }
}